home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14293 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: crl.crl.com!not-for-mail
  2. From: smuegge@crl.com (Shad Muegge)
  3. Newsgroups: comp.lang.c
  4. Subject: A little shift to the left and a little shift to the right.
  5. Date: 12 Apr 1996 22:36:22 -0700
  6. Organization: CRL Network Services      (415) 705-6060  [Login: guest]
  7. Message-ID: <4knegm$40d@crl.crl.com>
  8. NNTP-Posting-Host: crl.com
  9. X-Newsreader: TIN [version 1.2 PL2]
  10.  
  11. Our trusty PL/M-to-C translator generated the C operators << and >>
  12. whenever it encountered the PL/M operators SHL and SHR. 
  13.  
  14. In one case the original coder had used these bit shifting operators
  15. to clear out the top nibble of a byte using the following code. 
  16. (Actually this is the C code the translator generated less the
  17. proprietary variable names. :))
  18.  
  19.    x = ( ( y << 4 ) >> 4 );
  20.  
  21.    (The name of the coder will remain a secret, and yes I know a
  22.     simple "& 0x0f" would be a more obvious solution. but the same
  23.     problem is exhibited for any left-shift followed by a right-shift)
  24.  
  25. Both the variables x and y are bytes ( unsigned chars ). 
  26.  
  27. The results of this code is the the value of y is assigned to
  28. x without any modification.  The same results as simple assignment
  29. (x = y).  It turns out that every C compiler I've tried ( Intel-C,
  30. Microsoft VC++, and gcc) exhibits this same behaviour. 
  31. Looking at the assembly code generated by all three compilers the
  32. reason the shifts have no effect is because they do them with 32 
  33. bit registers.  So, when the bits are shifted to the left by 4 they
  34. aren't "lost" as one might expect.  Then the right shift just 
  35. returns all the bits to original position. 
  36.  
  37. By using a typecast two of the compilers (Intel-C and gcc) will 
  38. do what the original coder intended, mask off the the top nibble of
  39. a byte. Microsoft's compiler just ignored the typecast and 
  40. generated the same code as it did without the typecast.
  41.  
  42.   x = ( ( unsigned char ) ( y << 4 ) >> 4 );
  43.  
  44. Also, seperating the two shifts into two statements all the compilers
  45. work as originally hoped.
  46.  
  47.   x = y << 4;
  48.   x = x >> 4;
  49.  
  50. Anyway, any experts in C want to tell me whether these compilers
  51. are just doing these operations correctly or incorrectly?  Also,
  52. what about the fact that the Microsoft compiler ignores the typecast
  53. unlike Intel-C and gcc?  Also, if any experts in human behaviour
  54. want to tell me why I care, I would appreciate that too.
  55.  
  56. Shad
  57. smuegge@crl.com
  58.